package com.flashcash.kotlin.widget

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.Button
import com.flashcash.solu.R
import com.flashcash.kotlin.trace.LocalOnClickListener
import com.x.leo.apphelper.utils.TimeCounter
import com.x.leo.apphelper.utils.TimeCounter.TimerListener

/**
 * @作者:XLEO
 * @创建日期: 2017/9/1 15:01
 * @描述:${TODO}
 *
 * @更新者:${Author}$
 * @更新时间:${Date}$
 * @更新描述:${TODO}
 * @下一步：
 */
open class LocalButton(ctx: Context, attributeSet: AttributeSet?) : Button(ctx, attributeSet) {
    private var actionName: String = "no name set"
    private var doRestrictDoubleClick: Boolean = true

    init {
        if (attributeSet != null) {
            val attrs = ctx.obtainStyledAttributes(attributeSet, R.styleable.LocalButton)
            if (attrs.hasValue(R.styleable.LocalTextView_tActionName)) {
                actionName = attrs.getString(R.styleable.LocalTextView_tActionName)
            }
            doRestrictDoubleClick = attrs.getBoolean(R.styleable.LocalButton_restrictClick, true)
            attrs.recycle()
        }
    }

    override fun setOnClickListener(l: OnClickListener?) {
        super.setOnClickListener(if (doRestrictDoubleClick) {
            RestrictClickListener(actionName, l, this@LocalButton)
        } else
            LocalOnClickListener(actionName, l))
    }

    class RestrictClickListener(actionName: String?, l: OnClickListener?, val view: View?) : LocalOnClickListener(actionName, l) {
        private val counter = TimeCounter(3000, 1000, object : TimerListener {
            override fun onTick(millisUntilFinished: Long) {
                if (view != null && view?.isClickable) {
                    view.isClickable = false
                }
            }

            override fun onFinish() {
                view?.isClickable = true
            }
        })

        override fun onClick(v: View?) {
            view?.isClickable = false
            counter.start()
            super.onClick(v)
        }
    }
}